package com.suncaper.han_yi_system.service.impl;

import com.suncaper.han_yi_system.exception.CustomerException;
import com.suncaper.han_yi_system.pojo.dto.LoginDto;
import com.suncaper.han_yi_system.pojo.entity.LoginUser;
import com.suncaper.han_yi_system.service.LoginService;
import com.suncaper.han_yi_system.utils.JwtUtil;
import com.suncaper.han_yi_system.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    RedisCache redisCache;

    @Override
    public Map<String, Object> login(LoginDto loginDto) {

        // 封装成 Authentication 对象
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword());

        // 进行身份认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 判断是否认证成功
        if(Objects.isNull(authenticate)) {
            throw new CustomerException("用户名或密码错误！");
        }

        // 获取用户信息
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();

        // 使用userId生成token字符串
        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtUtil.USER_INFO_ID, userId);
        String jwt = JwtUtil.createJWT(claims);

        //存入Redis
        redisCache.setCacheObject("login:"+userId, loginUser);
        redisCache.expire("login:"+userId,JwtUtil.JWT_TTL);

        //返回token
        Map<String, Object> map = new HashMap<>();
        map.put("token",jwt);
        return map;

    }

    @Override
    public void logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        redisCache.deleteObject("login:"+userId);
    }
}